<template>
   <div class="content">
        <TableLayout form-title="">
            <div slot="form-title" class="table-title"></div>
            <!-- 当省管理时显示 -->
            <el-form :model="formInline" label-position="left" class="formInline" label-width="40px" slot="form" 
            v-if="showProvince">
                <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="省份">
                                <province v-model="formInline.fProvinceId" ref="province"></province>
                        </el-form-item>
                    </el-col>
                    <el-button type="primary" @click="search($route.name)">查询</el-button>
                </el-row>
            </el-form>
            <!-- 当市管理时显示 -->
            <el-form :model="formInline" label-position="left" class="formInline" label-width="40px" slot="form" v-if="showCity">
                 <el-row :gutter="41">
                    <el-col :span="8">
                         <el-form-item label="省份">
                                <province  v-model="formInline.fProvinceId" ></province>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="市" > 
                                <city v-model="formInline.fCityId" :province="formInline.fProvinceId" ref="city"></city>
                        </el-form-item>
                    </el-col>
                    <div class="btnPosition">
                        <el-button type="primary" @click="search($route.name)">查询</el-button>
                    </div>
                </el-row>
            </el-form>
             <!-- 当区管理时显示 -->
            <el-form :model="formInline" label-position="left" class="formInline" label-width="40px" slot="form" v-if="showArea">
                 <el-row :gutter="41">
                    <el-col :span="8">
                         <el-form-item label="省份">
                                <province  v-model="formInline.fProvinceId" ></province>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                         <el-form-item label="市" > 
                                <city v-model="formInline.fCityId" :province="formInline.fProvinceId"></city>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                         <el-form-item label="区县">
                                <region v-model="formInline.fAreaId" :city="formInline.fCityId" ref="area"></region>
                        </el-form-item>
                    </el-col>
                </el-row>
                   <div class="top-line">
                        <el-button type="primary" @click="search($route.name)">查询</el-button>
                    </div>
            </el-form>
            <div class="table-title" slot="table-title">
                 <div class="btnPosition">
                    <el-button @click="deleteRoleLots"  :disabled="true">批量删除</el-button>
                    <el-button @click="showAdd" :disabled="true">添加</el-button>
                </div>
            </div>
            <el-table :data="AnnounceList" border style="width: 100%" @selection-change="handleSelectionChange" 
            ref="multipleTable" v-loading="loading">
                <el-table-column type="selection" align="center" width="55"></el-table-column>
                <el-table-column align="center"  label="区名称" prop="areaName" min-width="120" 
                v-if="showAreaTable">
                </el-table-column>
                <el-table-column align="center" :label="cityLabelName" prop="cityName" min-width="120" 
                v-if="showCityTable">
                </el-table-column>
                <el-table-column align="center" :label="provinceLabelName"  prop="provinceName" min-width="80" 
                v-if="showProvinceTable">
                </el-table-column>
                <el-table-column label="其他操作" width="160">
                    <template scope="scope">
                        <el-button type="text" class="btn-success" 
                          @click="correctRow(scope.row)"  :disabled="true">修改</el-button>
                        <el-button type="text" class="btn-success" @click="deleteListOne(scope.row)"  :disabled="true">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container" style="text-align:right">
                <el-pagination layout="total, sizes, prev, pager, next, jumper" :total="listQuery.total" :current-page.sync="listQuery.page" :page-sizes="config.pageSizes" :page-size="config.pageSize" 
                @size-change="handleSizeChange" @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </TableLayout>
        <addAndCorrect ref="addAndCorrect" :addData.sync="addData" @searchList="searchOrCase"> </addAndCorrect>
    </div>
</template>
<script>
import TableLayout from 'components/TableLayout';
import { mapState, mapActions, mapGetters } from 'vuex';
import {queryHadProvince, queryHadCity, queryHadArea, deleteProvince, deleteCity, deleteArea} from 'api/system';
import addAndCorrect from './addAndCorrect';
import province from 'components/CascadeRegion/province';
import city from 'components/CascadeRegion/city';
import region from 'components/CascadeRegion/region';
export default {
    name: 'serarchList',
    components: { TableLayout, addAndCorrect, province, city, region},
    data() {
        return {
            formInline: { // 查询条件的表单数据 
                fProvinceId: '', // 省份
                fCityId: '', // 市区
                fAreaId: '' // 区县
            },
            routerName: '', // 当前管理页面名字
            AnnounceList: [], // 表格数据
            multipleSelection: [], // 勾选的表格的项目
            // 表格中是否显示省市区
            cityLabelName: '所属市名称',
            provinceLabelName: '所属省份名称',
            showProvinceTable: false,
            showCityTable: false,
            showAreaTable: false,
            loading: true, // 查询时的加载提示
            listQuery: { // 分页
                page: 1,
                total: 0
            },
            showProvince: false,
            showCity: false,
            showArea: false,
            // 点击修改、添加时，要传给子组件的信息
            addData: {
                dialogAdd: false,
                popTitle: '',
                status: '', // 点击添加或修改（1,2）
                // 修改按钮传给子组件的参数
                provinceName: '',
                provinceId: '',
                cityName: '',
                cityId: '',
                areaName: '',
                areaId: ''
            }
        };
    },
    computed: {
        ...mapState({
            config: state => state.config.table

        }),
        ...mapGetters(['uid'])
    },
    created() {
        this.routerName=this.$route.name;
        this.findWhoSearchList(this.$route.name);
    },
    methods: {
    // 全局获取行数
        ...mapActions(['ChangePageSize']),
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        
        // 添加操作按钮
        showAdd() {
            if (this.routerName == '省管理') {
                this.addData.popTitle='添加省级单位';
            }
            if (this.routerName == '市管理') {
                this.addData.popTitle='添加市级单位';
            }
            if (this.routerName == '区管理') {
                this.addData.popTitle='添加区级单位';
            }
            this.addData.dialogAdd = true;
            this.addData.status=1;
        },
        // 修改操作按钮
        correctRow(row) {
            this.addData.dialogAdd = true;
            this.addData.status=2;
            if (this.routerName == '省管理') {
                this.addData.popTitle='修改省级单位';
                this.addData.provinceName=row.provinceName;
                this.addData.provinceId=row.provinceId;
            } else if (this.routerName == '市管理') {
                this.addData.popTitle='修改市级单位';
                this.addData.provinceId=row.provinceId;
                this.addData.cityName=row.cityName;
                this.addData.cityId=row.cityId;
            } else if (this.routerName == '区管理') {
                this.addData.popTitle='修改区级单位';
                this.addData.provinceId=row.provinceId;
                this.addData.cityId=row.cityId;
                this.addData.areaName=row.areaName;
                this.addData.areaId=row.areaId;
            }
        },
    // 根据路由判断是在省管理、市管理、区管理
        findWhoSearchList(routerName) {
            this.search(routerName);// 自动判断在哪个管理页面，然后查询列表
            if (routerName == '省管理') {
                this.showProvince = true;
                this.showProvinceTable=true;
                this.provinceLabelName='省份名称';
            } else if (routerName == '市管理') {
                this.showCity = true;
                this.showProvinceTable = true;
                this.showCityTable=true;
                this.cityLabelName='市名称';
            } else if (routerName == '区管理') {
                this.showArea = true;
                this.showProvinceTable = true;
                this.showCityTable=true;
                this.showAreaTable=true;
            }
        },
        searchOrCase(searchOrCase) {
            if (searchOrCase=='search') {
                this.search(this.routerName);
            } else {
                this.searchFetchData(this.routerName);
            }

        },
        search(routerName) {
            this.listQuery.page = 1;
            this.searchFetchData(routerName);
        },
        // 点击查询列表
        searchFetchData(routerName) {
            if (routerName=='省管理') {
                this.getProvinceTableList()// 查询省列表
                // console.log(this.$refs, 'this.$refs');
                setTimeout(() => {
                    this.$refs.province.getList();
                }, 60)

            } else if (routerName=='市管理') {// 查询市列表
                this.getCityTableList();

                setTimeout(() => {
                    this.$refs.city.getList();
                }, 60)
            } else if (routerName=='区管理') {// 查询区列表
                this.getAreaTableList();
                setTimeout(() => {
                    this.$refs.area.getList();
                }, 60)
            }
        },
         // 单个删除
        deleteListOne(row) {
            this.$confirm('确定删除？', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: ' ', // warning
                title: '  '
            }).then(() => {
                if (this.routerName=='省管理') {
                    let provinceIds=row.provinceId;
                    this.deleteAndUpdateProvince(provinceIds)
                }
                if (this.routerName=='市管理') {
                    let cityIds=row.cityId;
                    this.deleteAndUpdateCity(cityIds)
                }
                if (this.routerName=='区管理') {
                    let areaIds=row.areaId;
                    this.deleteAndUpdateArea(areaIds)
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 批量删除
        deleteRoleLots() {
            let provinceIds = '';
            let cityIds = '';
            let areaIds = '';
            if (!this.multipleSelection.length) {
                this.$message({
                    type: 'info',
                    message: '请选择删除项！'
                });
                return false
            }
            if (this.routerName=='省管理') {
                for (let i = 0; i < this.multipleSelection.length; i++) {
                    provinceIds += this.multipleSelection[i].provinceId + ',';
                }
                provinceIds = provinceIds.substring(0, provinceIds.length - 1)
            }
            if (this.routerName=='市管理') {
                for (let i = 0; i < this.multipleSelection.length; i++) {
                    cityIds += this.multipleSelection[i].cityId + ',';
                }
                cityIds = cityIds.substring(0, cityIds.length - 1)
            }
            if (this.routerName=='区管理') {
                for (let i = 0; i < this.multipleSelection.length; i++) {
                    areaIds += this.multipleSelection[i].areaId + ',';
                }
                areaIds = areaIds.substring(0, areaIds.length - 1)
            }
            this.$confirm('此操作将批量删除, 是否继续?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                if (this.routerName=='省管理') {
                    this.deleteAndUpdateProvince(provinceIds)
                }
                if (this.routerName=='市管理') {
                    this.deleteAndUpdateCity(cityIds)
                }
                if (this.routerName=='区管理') {
                    this.deleteAndUpdateArea(areaIds)
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 删除省后更新列表
        deleteAndUpdateProvince(provinceIds) {
            this.loading=true;
            deleteProvince(provinceIds).then(res => {
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                // 回填省份select
                // provinceIds 删除的省的id
                // 如果当前省的select框的id已经不存在（ 省的select的省，在table列表已删除）
                if (this.formInline.fProvinceId==provinceIds) {// 回填（请选择）
                    // console.log('当前select省的id是删除的id');
                        // this.searchAllProvice();
                    let status=0;// 代表删除了该id
                    this.getProvinceTableList(status);
                } else {
                    this.getProvinceTableList();
                }
                setTimeout(() => {
                    this.$refs.province.getList();
                }, 60)
               
            }).catch(() => {
                this.loading = false;
            });
        },
        // 删除市后更新列表
        deleteAndUpdateCity(cityIds) {
            this.loading=true;
            deleteCity(cityIds).then(res => {
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                if (this.formInline.fCityId==cityIds) {// 回填（请选择）
                    let status=0;
                    this.getCityTableList(status);
                } else {
                    let status=1;
                    this.getCityTableList(status);
                }
                setTimeout(() => {
                    this.$refs.city.getList();
                }, 60)
               
            }).catch(() => {
                this.loading = false;
            });
        },
        // 删除区后更新列表
        deleteAndUpdateArea(areaIds) {
            this.loading=true;
            deleteArea(areaIds).then(res => {
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                if (this.formInline.fAreaId==areaIds) {// 回填（请选择）删除的是选中
                    let status=0;
                    this.getAreaTableList(status);
                } else {
                    this.getAreaTableList();
                }
                setTimeout(() => {// 刷新区的列表
                    this.$refs.area.getList();
                }, 60)
               
            }).catch(() => {
                this.loading = false;
            });
        },
     // 查询所有省份
        getProvinceTableList(status) {
            let provinceId=this.formInline.fProvinceId;
            let curPage = this.listQuery.page;
            let pageSize = this.config.pageSize;
            if (status==0) {// 已删除
                this.formInline.fProvinceId='';
                provinceId='';
            }
            this.loading = true;
            queryHadProvince(provinceId, curPage, pageSize).then(res => {
                if (res.data.status==200) {
                    this.AnnounceList = res.data.content.list;
                    this.listQuery.total = res.data.content.pagination.total;
                    this.loading = false;
                } else {
                    this.$message.error(res.data.errorMsg);
                }
            }).catch(() => {
                this.loading = false;
            });
        },
        // 查询所有的市
        getCityTableList(status) {
            // console.log('查询所有的市');
            let provinceId = this.formInline.fProvinceId;// 参数
            let cityId = this.formInline.fCityId;
            let curPage = this.listQuery.page;
            let pageSize = this.config.pageSize;
            if (status==0) {// 已删除
                this.formInline.fCityId='';// 回填
                cityId='';
            }
            this.loading = true;
            queryHadCity(provinceId, cityId, curPage, pageSize).then(res => {
                if (res.data.status==200) {
                    this.AnnounceList = res.data.content.list;
                    this.listQuery.total = res.data.content.pagination.total;
                    this.loading = false;
                } else {
                    this.$message.error(res.data.errorMsg);
                }
            }).catch(() => {
                this.loading = false;
            });
        },
        // 查询所有的区
        getAreaTableList(status) {
            let provinceId = this.formInline.fProvinceId; // 参数
            let cityId = this.formInline.fCityId;
            let areaId = this.formInline.fAreaId;
            let curPage = this.listQuery.page;
            let pageSize = this.config.pageSize;
            if (status==0) {// 已删除
                this.formInline.fAreaId='';
                areaId='';
            }
            this.loading = true;
            queryHadArea(provinceId, cityId, areaId, curPage, pageSize).then(res => {
                if (res.data.status==200) {
                    this.AnnounceList = res.data.content.list;
                    this.listQuery.total = res.data.content.pagination.total;
                    this.loading = false;
                } else {
                    this.$message.error(res.data.errorMsg);
                }
            }).catch(() => {
                this.loading = false;
            });
        },
        handleSizeChange(val) {// 分页
            this.listQuery.page = 1;
            this.ChangePageSize(val);
            this.searchFetchData(this.$route.name);
        },
        handleCurrentChange(val) {
            this.listQuery.page = val;
            this.searchFetchData(this.$route.name);
        }
    }
};
</script>
<style lang="scss" scoped>
.content {
  position: relative;
  padding: 0px;
  $bgcolor: #fff;
  .formInline {
    .formBtn {
      width: 100%;
      height: 70px;
      border-top: 1px solid #dddddd;
      position: relative;
      .btnPosition {
        position: absolute;
        right: 0px;
        top: 18px;
      }
    }
  }
}
</style>